package com.tmindtech.api.mas.controller;

import com.jasson.im.api.APIClient;
import com.tmindtech.api.mas.configuration.MasConfiguration;
import com.tmindtech.api.mas.dto.SendingResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@RestController
public class MasController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MasController.class);

    private MasConfiguration masConfiguration;

    public MasController(MasConfiguration masConfiguration) {
        this.masConfiguration = masConfiguration;
    }

    @PostMapping("/send")
    public SendingResult sendMessage(@RequestParam String phone, @RequestParam String content, @RequestParam Long smId) {
        String decodedContent;
        try {
            decodedContent = URLDecoder.decode(content, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new SendingResult(-6);
        }
        LOGGER.info("Receive new sms task, phone: {}, smId: {}, content: \n{}", phone, smId, decodedContent);
        APIClient apiClient = new APIClient();
        int initResult = apiClient.init(
                masConfiguration.getHostIp(),
                masConfiguration.getLoginName(),
                masConfiguration.getLoginPassword(),
                masConfiguration.getApiId(),
                masConfiguration.getDbName()
        );
        if (initResult != 0) {
            LOGGER.error("Task with smId {} for phone {} failed, code: {}", smId, phone, initResult);
            return new SendingResult(initResult);
        }
        int sendResult = apiClient.sendSM(phone, decodedContent, smId);
        LOGGER.info("Task with smId {} for phone {} get code {}", smId, phone, sendResult);
        return new SendingResult(sendResult);
    }
}
